import logging
import time

from src.common.prj_path import get_abs_path
from src.common.utils import read_yaml

LOG = logging.getLogger()


class QianNiuApp(object):
    def __init__(self):
        self.product_yaml_path = get_abs_path('privacy', 'product.yaml')
        self.product = read_yaml(self.product_yaml_path)
        self.product_name = None
        self.order_dict = {}

    def get_send_text(self):
        if not self.product_name or self.product_name not in self.product:
            err_msg = 'not support this product={}'.format(self.product_name)
            LOG.error(err_msg)
            raise Exception(err_msg)
        else:
            function = getattr(self, self.product[self.product_name]['send_way'])
            return function()

    def get_order_dict(self, text_list):
        def get_name_price_num(str1):
            list1 = str1.split(' ')
            num = list1[-1][1:]
            price = list1[-2][1:]
            name = ' '.join(list1[:-2])
            LOG.debug('name={}, price={}, num={}'.format(name, price, num))
            return name, price, num

        order_dict = {}
        for i, item in enumerate(text_list):
            if '订单编号：' in item:
                product_name, product_price, product_number = get_name_price_num(text_list[i + 2])
                order_number = text_list[i][5:]
                order = {
                    'order_number': order_number,
                    'buyer': text_list[i - 1],
                    'product_price': product_price,
                    'product_name': product_name,
                    'product_number': product_number,
                }
                order_dict.update({order_number: order})
        self.order_dict = order_dict
        for value in self.order_dict.values():
            self.product_name = value['product_name']
            value['text'] = self.get_send_text()
        LOG.debug('解析得到订单为={}'.format(order_dict))
        return order_dict

    def just_text(self):
        return self.product[self.product_name]['text']

    def get_one_buyer_name(self):
        for order_number, value in self.order_dict.items():
            return value['buyer']

    def get_one_buyer_text(self):
        for order_number, value in self.order_dict.items():
            return value['text']

    def if_notification_have_buyer(self, text):
        LOG.debug('通知={}'.format(text))
        return '买家已付款' in text

    def wait_some_time(self, seconds):
        if isinstance(seconds, str):
            seconds = int(seconds)
        time.sleep(seconds)



if __name__ == '__main__':
    a = QianNiuApp()
    a.product_name = 'python3.8安装包'
    print(a.get_send_text())
